#include "stdafx.h"
#include "script/luaex/luaex.h"
#include "roles/player/playermgr.h"
#include "roles/enemy/enemymgr.h"
#include "./gamemgr.h"
#include "./gamewrapper.h"

luaobj GameWrapper::s_playersTbl;
luaobj GameWrapper::s_enemiesTbl;
int GameWrapper::s_enemiesCount = 0;

namespace{
	GameWrapper s_gamewarpper;
}

void Output(string str)
{
	::OutputDebugStringA((str + "\n").c_str());
}

int Test(lua_State* L)
{
	Player* p = (Player*)lua_touserdata(L, 1);

	return 0;
}


GameWrapper::GameWrapper()
{
	Def_Module("Game")
	[
		Def_Function("GetStageSize", &GameWrapper::GetStageSize),
		Def_Lua_Function("GetPlayers", &GameWrapper::GetPlayers),
		Def_Lua_Function("GetEnemies", &GameWrapper::GetEnemies),
		Def_Lua_Function("Test", &Test),
		Def_Function("Output", &Output)
	];

	lua_newtable(LuaEx::GetInstance().GetLuaState());
	s_playersTbl->InitObj(luaL_ref(LuaEx::GetInstance().GetLuaState(), LUA_REGISTRYINDEX));

	lua_newtable(LuaEx::GetInstance().GetLuaState());
	s_enemiesTbl->InitObj(luaL_ref(LuaEx::GetInstance().GetLuaState(), LUA_REGISTRYINDEX));
}

GameWrapper::~GameWrapper()
{

}

void GameWrapper::UpdatePlayersTbl()
{
	s_playersTbl->PushObj(LuaEx::GetInstance().GetLuaState());

	int count = 1;
	vector<Player*>& playerlist = PlayerMgr::GetInstance().GetPlayers();
	vector<Player*>::iterator iter;
	for (iter = playerlist.begin(); iter != playerlist.end(); ++iter)
	{
		Player* player = *iter;

		luaobj& playerobj = reinterpret_cast<PlayerAI*>(player)->GetPlayerObj();
		playerobj->PushObj(LuaEx::GetInstance().GetLuaState());	//value
		lua_rawseti(LuaEx::GetInstance().GetLuaState(), -2, count++);
	}
}

void GameWrapper::UpdateEnemiesTbl(int count)
{
	s_enemiesTbl->PushObj(LuaEx::GetInstance().GetLuaState());
	for (int i = s_enemiesCount; i < count; ++i)
	{
		Enemy* pEnemy = EnemyMgr::GetInstance().GetEnemy(i);
		luaobj& enemyobj = reinterpret_cast<EnemyAI*>(pEnemy)->GetEnemyObj();
		enemyobj->PushObj(LuaEx::GetInstance().GetLuaState());	//value
		lua_rawseti(LuaEx::GetInstance().GetLuaState(), -2, i + 1);
	}

	s_enemiesCount = count;

	lua_pop(LuaEx::GetInstance().GetLuaState(), 1);
}

Size GameWrapper::GetStageSize()
{
	return GameMgr::GetInstance().GetStageSize();
}

int GameWrapper::GetPlayers(lua_State* luaState)
{
	s_playersTbl->PushObj(luaState);
	return 1;
}

int GameWrapper::GetEnemies(lua_State* luaState)
{
	s_enemiesTbl->PushObj(luaState);
	return 1;
}